import { udp } from '@cscec/udp-ui';
import type { ICustomHooks, IListPage } from '../interface';
import { getRequestByConfig } from '../service';
import { $ImpSdk } from '@cscec/udp-ui';
/**
 * 内置页面控制器
 */
export default function initListController(page: IListPage) {
  udp.PageReady<ICustomHooks>(() => ({}));
  const listInfo = page.getLayout();  //返回uiInfo，对应列表就是listInfo,编辑就是editInfo
  const capacity = page.getCapacity();

  udp.AllReady(
    (listPage: IListPage, { useAction }) => {
      const { busType } = listPage;
      // 新增
      useAction('onClick')(async () => {
        if(capacity.bizFlowFlag == 0){
          await listPage.openDetail(listPage.OType.Add);
        }else{
          const [rc, result] = await $ImpSdk.flowHelp({
              bizCode: busType,
              bizType: 0,
          });

          if (rc) {
            const uiSchemeId = result.interfaceSchemeId;
            const query: any = { oType: listPage.OType.Add, flowCode: result.flowCode };
            uiSchemeId && (query.ui_scheme_id = uiSchemeId);

            const {oType, record, ...other} = query ;
            listPage.openDetail(oType, record, other);
            // udp.open('/${bizName}/detail', query);
          } else {
            await listPage.openDetail(listPage.OType.Add);
            // udp.open('/${bizName}/detail', { oType: listPage.OType.Add });
          }
        }
      }, `${busType}_toolbar.add`);

      // 查看
      useAction('onClick')(async () => {
        const currentRecord = await listPage.getCurrentRecord();
        if (currentRecord) {
          await listPage.openDetail(listPage.OType.View, currentRecord);
        }
      }, `${busType}_toolbar.view`);

      // 修改
      useAction('onClick')(async () => {
        const currentRecord = await listPage.getCurrentRecord();
        if (currentRecord) {
          const wfFlg = currentRecord.wf_flg;
          if (wfFlg) {
            const result = await udp.confirm('该单据已送审或已审核，不允许修改，是否以查看方式打开?');
            if (result) {
              await listPage.openDetail(listPage.OType.View, currentRecord);
            }
          } else {
            await listPage.openDetail(listPage.OType.Edit, currentRecord);
          }
        }
      }, `${busType}_toolbar.edit`);

      // 删除
      useAction('onClick')(async () => {
        const busKey = listPage.getBusKey();
        const selectedRecord = listPage.getSelectedRecord();
        if (!selectedRecord.length) {
          await udp.alert('请先选择数据行');
          return;
        }

        if (selectedRecord.some(r => [1, 2].includes(r.wf_flg))) {
          await udp.alert('选择数据行存在已送审或审批的单据，不能执行删除操作！');
          return;
        }

        const result = await udp.confirm('是否删除记录?');
        if (result) {
          const hooks = await listPage.createHooks();
          const hookReturn = await hooks.transferDeleteReqParams?.(selectedRecord);
          if (hookReturn?.cancel) {
            return;
          }

          try {
            const keys = selectedRecord.map((r) => r[busKey]);
            const { ids, ...payload } = { ids: keys, bizCode: busType, ...hookReturn?.params };

            const localRequest = getRequestByConfig(
                listPage.getMicroServiceName(), 
                listInfo.requestDelete || {
                  method: 'body',
                  url: '/customForm/customPC/delete',
                }
            );
            const { code, message } = await localRequest({
              params: payload,
              data: ids
            });
            
            if (code === 0) {
              await listPage.refreshList();
            } else {
              await udp.alert(message);
            }
          } catch (e) {
            console.log(e);
            await udp.alert('删除失败，服务端接口错误');
          }
        }
      }, `${busType}_toolbar.delete`, { loading: '正在删除' });

      // 生成目的单
      useAction('onClick')(async () => {
        const size = await listPage.getSelectedRecord().length;
        if (!size) {
          udp.alert("请先选择数据行！");
        } else if (size > 1) {
          udp.alert("只能选一条！");
        } else {
          const currentRecord = await listPage.getCurrentRecord();
          // imp 推
          const [rc, result] = await $ImpSdk.flowHelp({
              bizCode: busType,
              bizType: 1,
          });
          if (rc) {
              const params = {
                  flowCode: result.flowCode,
                  instanceId: currentRecord?.flowInstanceId,
                  bizCode: busType,
                  autoOpen: true,
                  bizId: currentRecord?.id
              };
              const rv = await $ImpSdk.pushBill(params);
              console.log(rv);
          } else {
            await listPage.openDetail(listPage.OType.Add, currentRecord);
          }
        }
      }, `${busType}_toolbar.push_bill`);

      // 审核
      useAction('onClick')(
        async () => {
          // TODO
        },
        `${busType}_toolbar.verify`,
        { loading: '正在审核' },
      );

      // 去审核
      useAction('onClick')(
        async () => {
          // TODO
        },
        `${busType}_toolbar.unverify`,
        { loading: '正在去审核' },
      );

      // 送审
      useAction('onClick')(async () => {
        const selectedRecord = await listPage.getSelectedRecord();
        if (!selectedRecord.length) {
          await udp.alert('请先选择数据行');
          return;
        }
        const [success] = await listPage.startFlow(selectedRecord);
        if (success) {
          await listPage.refreshList();
        }
      }, `${busType}_toolbar.check`);

       // 申请去审
       useAction('onClick')(async () => {
        const currentRecord = await listPage.getCurrentRecord();
        if (!currentRecord) {
          return;
        }
        const [success] = await listPage.applyForReview(currentRecord);
        if (success) {
          await listPage.refreshList();
        }
      }, `${busType}_toolbar.applyForReview`);

      // 送审追踪
      useAction('onClick')(async () => {
        const currentRecord = await listPage.getCurrentRecord();
        if (currentRecord) {
          await listPage.getWorkFlow().showFlowInfo?.(listPage.busType, currentRecord[listPage.getBusKey()]);
        }
      }, `${busType}_toolbar.history`);
    },
    null,
    { delay: false },
  );
}
